#include "myqgsmaptoolpan.h"
#include "qgsmapview.h"
#include <qgsmaptoolpan.h>
#include <qgsproviderregistry.h>
#include <qgsrasterlayer.h>
#include <qgsvectorlayer.h>
#include <qgsvertexmarker.h>
#include <qgsfeature.h>
#include <qgsgeometry.h>
#include <qgslinestring.h>
#include <QVBoxLayout>
MapWidget::MapWidget(QWidget *parent)
: QWidget(parent)
{
    m_mapCanvas = new MyMapCanvas();
    initialize();
}

QgsPointXY MapWidget::tranforomCrs(float lon, float lat)
{
    QgsCoordinateReferenceSystem sourceCrs("EPSG:4326");
    QgsCoordinateReferenceSystem targetCrs("EPSG:3857");
    QgsCoordinateTransform transform(sourceCrs, targetCrs, QgsProject::instance());

    // 示例：转换一个点的坐标
    QgsPointXY pointIn4326(lon, lat); // 北京的经纬度
    QgsPointXY pointIn3857 = transform.transform(pointIn4326);
    return pointIn3857;
}

void MapWidget::initialize()
{
    // 初始化QGIS应用
    QgsApplication::setPrefixPath("/usr/bin/qgis", true);
    QgsApplication::init();
    QgsApplication::initQgis();

    // 初始化提供者注册表
    QgsProviderRegistry::instance("/usr/lib/qgis/plugins");

    qDebug() << "111111111111111111111";

   // m_mapCanvas = new QgsMapCanvas();
    m_mapCanvas->setVisible(true);
    m_mapCanvas->setCanvasColor(Qt::white);
   // m_mapCanvas->resize(800, 600);
    m_mapCanvas->enableAntiAliasing(true);

    // 设置布局
    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->addWidget(m_mapCanvas);
    setLayout(layout);

    // // 监听鼠标事件
    // m_mapCanvas->installEventFilter(this);

    QString tilePath = QString("/home/liubu/桌面/test.mbtiles");
    qDebug() << "tilePath =" << tilePath;
    // 加载地图图层
    QgsRasterLayer *layer = new QgsRasterLayer(tilePath, "Offline TianDiTu");
    qDebug() << "layer->isValid =" << layer->isValid() << layer->crs().description();
    if (!layer->isValid()) {
        qDebug() << "layer wrong";
        return;
    }

    QgsProject::instance()->addMapLayer(layer);

    // 获取图层的范围
    QgsRectangle layerExtent = layer->extent();

    // 设置画布的范围为图层的范围
    m_mapCanvas->setExtent(layerExtent);

    // 设置画布的大小为图层的大小
    m_mapCanvas->resize(QSize(layerExtent.width(), layerExtent.height()));
    m_mapCanvas->setLayers(QList<QgsMapLayer *>() << layer);
    // 刷新地图画布
    m_mapCanvas->refresh();

    // // 启用拖拽功能
    MyQgsMapToolPan *panTool = new MyQgsMapToolPan(m_mapCanvas);
    m_mapCanvas->setMapTool(panTool);

    // 添加矢量层
    QString vectorLayerName = "Trajectory Layer";
    QString vectorLayerUri = "LineString";
    QgsVectorLayer *vectorLayer = new QgsVectorLayer(vectorLayerUri, vectorLayerName, "memory");
    vectorLayer->setName("LineLayer");
    vectorLayer->setCrs(layer->crs());
    if (!vectorLayer->isValid()) {
        qDebug() << "Failed to create vector layer!";
        return ;
    }
    // 将矢量图层添加到地图画布
    QgsProject::instance()->addMapLayer(vectorLayer);

    // 添加轨迹线条
    testTraceLine(vectorLayer, layer);


    QgsVectorLayer *vectorPointLayer = new QgsVectorLayer("Point", "PointLayer", "memory");
    vectorPointLayer->setName("PointLayer");
    vectorPointLayer->setCrs(layer->crs());
    if (!vectorPointLayer->isValid()) {
        qDebug() << "Failed to create vector layer!";
        return ;
    }
    // 将矢量图层添加到地图画布
    QgsProject::instance()->addMapLayer(vectorPointLayer);

    // 添加轨迹点
    testTracePoint(vectorPointLayer, layer);


    //m_mapCanvas->setExtent(layer->extent());
    QgsAnnotationLayer *annotationLayer = new QgsAnnotationLayer("Annotations", QgsAnnotationLayer::LayerOptions(QgsProject::instance()->transformContext()));
    QgsProject::instance()->addMapLayer(annotationLayer);
    // QgsPointXY point = m_mapCanvas->getCoordinateTransform()->toMapCoordinates(QPoint(50, 50));
    // QgsAnnotationPointTextItem *textItem = new QgsAnnotationPointTextItem("11111", point);
    // annotationLayer->addItem(textItem);
    m_mapCanvas->setAnnotationLayer(annotationLayer);


    m_mapCanvas->setLayers(QList<QgsMapLayer *>()  << annotationLayer << vectorPointLayer << vectorLayer   << layer);

    // 刷新地图画布
    m_mapCanvas->refresh();


    // QgsVertexMarker* marker = new QgsVertexMarker(m_mapCanvas);
    // QgsPointXY pointIn3857 = tranforomCrs(lon, lat);
    // qDebug() << pointIn3857.toString();
    // marker->setCenter(pointIn3857);  // lon, lat 为目标点的经纬度
    // marker->setIconType(QgsVertexMarker::ICON_CIRCLE);
    // marker->setColor(Qt::red);
    // marker->setIconSize(10);
    // marker->setPenWidth(2);

    // QgsVertexMarker* marker1 = new QgsVertexMarker(m_mapCanvas);
    // QgsPointXY pointIn38571 = tranforomCrs(lon + 1, lat + 1);
    // qDebug() << pointIn3857.toString();
    // marker1->setCenter(pointIn38571);  // lon, lat 为目标点的经纬度
    // marker1->setIconType(QgsVertexMarker::ICON_CIRCLE);
    // marker1->setColor(Qt::green);
    // marker1->setIconSize(10);
    // marker1->setPenWidth(2);
}

void MapWidget::loadMap(const QString &path)
{
    // 加载地图图层
    QgsVectorLayer *layer = new QgsVectorLayer(path, "Map Layer");
    if (layer->isValid()) {
        m_mapCanvas->setExtent(layer->extent());
        m_mapCanvas->setLayers(QList<QgsMapLayer *>() << layer);
        m_mapCanvas->refresh();
    }
}

void MapWidget::testTracePoint(QgsVectorLayer *vectorLayer, QgsRasterLayer *layer)
{
    double lon = -86.963;
    double lat = 36.894;
    QgsPointXY point1 = tranforomCrs(lon, lat);
    QgsPointXY point2 = tranforomCrs(lon + 1, lat + 1);
    QgsPointXY point3 = tranforomCrs(lon + 1, lat + 2);

    QList<QgsPointXY> points;
    points << point1 << point2 << point3;
    QgsFeatureList features;
    for (const QgsPointXY &point : points) {
        QgsFeature feature;
        feature.setGeometry(QgsGeometry::fromPointXY(point));
        features.append(feature);
    }

    vectorLayer->dataProvider()->addFeatures(features);
    vectorLayer->updateExtents();


}

void MapWidget::testTraceLine(QgsVectorLayer *vectorLayer, QgsRasterLayer *layer)
{
    // 添加轨迹
    double lon = -86.963;
    double lat = 36.894;
    QgsPointXY point1 = tranforomCrs(lon, lat);
    QgsPointXY point2 = tranforomCrs(lon + 1, lat + 1);
    QgsPointXY point3 = tranforomCrs(lon + 1, lat + 2);
    QgsFeature feature;
    QgsLineString *lineString = new QgsLineString();
    QList<QgsPointXY> points;
    points << point1 << point2 ;

    for (const QgsPointXY &point : points) {
        lineString->addVertex(QgsPoint(point.x(), point.y()));
    }


    feature.setGeometry(QgsGeometry(lineString));
    QgsFeatureList features;
    features << feature;
    vectorLayer->dataProvider()->addFeatures(features);
    vectorLayer->updateExtents();

    m_mapCanvas->setExtent(layer->extent());
    m_mapCanvas->setLayers(QList<QgsMapLayer *>()  << vectorLayer << layer);

    // 刷新地图画布
    m_mapCanvas->refresh();

    m_mapCanvas->setLastPoint(point3);
    // 更新轨迹
    lineString->addVertex(QgsPoint(point3.x(), point3.y()));
    feature.setGeometry(QgsGeometry(lineString));
    features << feature;
    vectorLayer->dataProvider()->addFeatures(features);
    vectorLayer->updateExtents();
    m_mapCanvas->refresh();

}

bool MapWidget::eventFilter(QObject *obj, QEvent *event)
{
    // qDebug() << "obj = " << obj << ", event.type = " << event->type();
    // if (obj == m_mapCanvas) {
    //     if (event->type() == QEvent::MouseButtonPress) {
    //         QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
    //         qDebug() << "Mouse pressed at:" << mouseEvent->pos();
    //         // 在这里处理鼠标点击事件
    //         return true;
    //     } else if (event->type() == QEvent::MouseMove) {
    //         // QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
    //         // qDebug() << "Mouse moved to:" << mouseEvent->pos();
    //         // 在这里处理鼠标移动事件
    //         return true;
    //     }
    // }
}
